﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SQLite;
using System.Collections.ObjectModel;

namespace KeyboardImageViewer
{
    /// <summary>
    /// Interaction logic for ViewLists.xaml
    /// </summary>
    public partial class ViewLists : Window
    {
        public ViewLists()
        {
            InitializeComponent();

            ImageManager.Config.ApplyWindowSize("ViewLists", this);

            this.PopulateListBox();
            this.viewListsBox.SelectionChanged += new SelectionChangedEventHandler(viewListsBox_SelectionChanged);
        }

        private void viewListsBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bool itemSelected = this.viewListsBox.SelectedIndex >= 0;

            this.editListButton.IsEnabled = itemSelected;
            this.showListButton.IsEnabled = itemSelected;
            this.deleteListButton.IsEnabled = itemSelected;
            this.setAsStartListButton.IsEnabled = itemSelected;
            this.upButton.IsEnabled = itemSelected;
            this.downButton.IsEnabled = itemSelected;

            if (itemSelected)
            {
                if (this.viewListsBox.SelectedIndex == 0)
                {
                    this.upButton.IsEnabled = false;
                }
                else if (this.viewListsBox.SelectedIndex == this.viewListsBox.Items.Count - 1)
                {
                    this.downButton.IsEnabled = false;
                }

                int selectedListId = (int)((ListBoxItem)this.viewListsBox.SelectedItem).Tag;
                if (selectedListId == ImageManager.Config.StartingListId)
                {
                    this.deleteListButton.IsEnabled = false;
                    this.setAsStartListButton.IsEnabled = false;
                }
            }
        }

        private void lbi_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.ShowSelectedList();
            this.DialogResult = true;
        }

        private void PopulateListBox()
        {
            this.viewListsBox.Items.Clear();

            SQLiteCommand command = new SQLiteCommand("SELECT id, name FROM viewLists ORDER BY listIndex", ImageManager.Connection);
            using (SQLiteDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    int listId = reader.GetInt32("id");
                    string name = reader.GetString("name");

                    ListBoxItem listBoxItem = new ListBoxItem();

                    if (listId == ImageManager.Config.StartingListId)
                    {
                        StackPanel viewListPanel = new StackPanel();
                        viewListPanel.Orientation = Orientation.Horizontal;
                        TextBlock viewListNameBlock = new TextBlock { Text = name };
                        viewListPanel.Children.Add(viewListNameBlock);
                        TextBlock startingIdentifierBlock = new TextBlock();
                        Run italicText = new Run { FontStyle = FontStyles.Italic, FontWeight = FontWeights.Bold, Text = "(Starting List)" };
                        startingIdentifierBlock.Inlines.Add(italicText);
                        startingIdentifierBlock.Margin = new Thickness(6, 0, 0, 0);
                        viewListPanel.Children.Add(startingIdentifierBlock);
                        listBoxItem.Content = viewListPanel;
                    }
                    else
                    {
                        listBoxItem.Content = name;
                    }

                    listBoxItem.Tag = listId;
                    listBoxItem.MouseDoubleClick += new MouseButtonEventHandler(lbi_MouseDoubleClick);

                    ContextMenu menu = new ContextMenu();

                    MenuItem editItem = new MenuItem();
                    editItem.Header = "Edit";
                    editItem.Click += new RoutedEventHandler(this.EditList);
                    menu.Items.Add(editItem);

                    if (listId != ImageManager.Config.StartingListId)
                    {
                        MenuItem deleteItem = new MenuItem();
                        deleteItem.Header = "Delete";
                        deleteItem.Click += new RoutedEventHandler(this.DeleteList);

                        /*BitmapImage deleteBitmapImage = new BitmapImage();
                        deleteBitmapImage.BeginInit();
                        deleteBitmapImage.UriSource = new Uri("/remove.png", UriKind.RelativeOrAbsolute);
                        deleteBitmapImage.EndInit();
                        Image deleteImage = new Image();
                        deleteImage.Width = 20;
                        deleteImage.Source = deleteBitmapImage;
                        deleteItem.Icon = deleteImage;*/

                        menu.Items.Add(deleteItem);

                        MenuItem setAsStartListItem = new MenuItem();
                        setAsStartListItem.Header = "Set as Start List";
                        setAsStartListItem.Click += new RoutedEventHandler(this.SetAsStartList);
                        menu.Items.Add(setAsStartListItem);
                    }

                    listBoxItem.ContextMenu = menu;

                    this.viewListsBox.Items.Add(listBoxItem);
                }
            }
        }

        private void newListButton_Click(object sender, RoutedEventArgs e)
        {
            EditViewList editViewList = new EditViewList(-1, this.viewListsBox.Items.Count);
            editViewList.Owner = this;
            editViewList.ShowDialog();

            int selectedIndex = this.viewListsBox.SelectedIndex;
            this.PopulateListBox();
            this.viewListsBox.SelectedIndex = selectedIndex;
        }

        private void EditList(object sender, RoutedEventArgs e)
        {
            if (this.viewListsBox.SelectedIndex >= 0)
            {
                EditViewList editViewList = new EditViewList((int)((ListBoxItem)this.viewListsBox.SelectedItem).Tag, -1);
                editViewList.Owner = this;
                editViewList.ShowDialog();

                int selectedIndex = this.viewListsBox.SelectedIndex;
                this.PopulateListBox();
                this.viewListsBox.SelectedIndex = selectedIndex;
            }
        }

        private void DeleteList(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Really delete the list?", "Confirm delete", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                int idToDelete = (int)((ListBoxItem)this.viewListsBox.SelectedItem).Tag;

                using (SQLiteTransaction transaction = ImageManager.Connection.BeginTransaction())
                {
                    Database.ExecuteNonQuery("DELETE FROM viewLists WHERE id = " + idToDelete, ImageManager.Connection);

                    this.RefreshListIndices();

                    transaction.Commit();
                }

                this.PopulateListBox();
            }
        }

        private void SetAsStartList(object sender, RoutedEventArgs e)
        {
            ImageManager.Config.StartingListId = (int)((ListBoxItem)this.viewListsBox.SelectedItem).Tag;

            int selectedIndex = this.viewListsBox.SelectedIndex;
            this.PopulateListBox();
            this.viewListsBox.SelectedIndex = selectedIndex;
        }

        private void showListButton_Click(object sender, RoutedEventArgs e)
        {
            this.ShowSelectedList();
            this.DialogResult = true;
        }

        private void ShowSelectedList()
        {
            int idToDisplay = (int)((ListBoxItem)this.viewListsBox.SelectedItem).Tag;

            QueryOperations.ShowImageList(idToDisplay);
        }

        private void RefreshListIndices()
        {
            for (int i = 0; i < this.viewListsBox.Items.Count; i++)
            {
                ListBoxItem item = (ListBoxItem)this.viewListsBox.Items[i];
                int itemId = (int)item.Tag;

                Database.ExecuteNonQuery("UPDATE viewLists SET listIndex = " + i + " WHERE id = " + itemId, ImageManager.Connection);
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            ImageManager.Config.SaveWindowSize("ViewLists", this);
        }

        private void upButton_Click(object sender, RoutedEventArgs e)
        {
            int selectedIndex = this.viewListsBox.SelectedIndex;

            ListBoxItem itemToMove = (ListBoxItem)this.viewListsBox.SelectedItem;
            this.viewListsBox.Items.Remove(itemToMove);

            this.viewListsBox.Items.Insert(selectedIndex - 1, itemToMove);

            using (SQLiteTransaction transaction = ImageManager.Connection.BeginTransaction())
            {
                this.RefreshListIndices();

                transaction.Commit();
            }

            this.viewListsBox.SelectedIndex = selectedIndex - 1;
        }

        private void downButton_Click(object sender, RoutedEventArgs e)
        {
            int selectedIndex = this.viewListsBox.SelectedIndex;

            ListBoxItem itemToMove = (ListBoxItem)this.viewListsBox.SelectedItem;
            this.viewListsBox.Items.Remove(itemToMove);

            this.viewListsBox.Items.Insert(selectedIndex + 1, itemToMove);

            using (SQLiteTransaction transaction = ImageManager.Connection.BeginTransaction())
            {
                this.RefreshListIndices();

                transaction.Commit();
            }

            this.viewListsBox.SelectedIndex = selectedIndex + 1;
        }
    }
}
